package com.fubowen.reader.components

import java.util.Timer
import java.util.TimerTask

class InvokeTimer {

    private lateinit var timer: Timer
    var isRunning = false

    fun start(ms: Long, invoke: () -> Unit) {
        val task = object : TimerTask() {
            override fun run() = invoke()
        }
        timer = Timer()
        timer.schedule(task, ms, ms)
        isRunning = true
    }

    fun stop() {
        timer.cancel()
        timer.purge()
        isRunning = false
    }

    fun toggle(ms: Long, invoke: () -> Unit) {
        isRunning = !isRunning
        if (isRunning) {
            start(ms, invoke)
        } else {
            stop()
        }
    }
}